
import { getRecinvoicesList, approval, receiveinvoice, checkinvoice, batchCheckinvoice } from '../../services/drawback/recinvoices';
import { getInvoicesList, preinvoiceopen, inoviceheader, inoviceproducts, queryDrawers, taxpreopeninvoice } from '../../services/drawback/invoice';

import Constants from '../../utils/Constants';
import { message } from "antd";
const R = require('ramda');

export default {
    namespace: 'recinvoices',
    state: {
        page: {
            page: 1,
            size: 10,
            totalRow: 0,
            totalPage: 0
        },

        list: [],
        dataSource: {},
        inoviceheader: {},
        inoviceproductsList: [],
        taxpreopeninvoice: {},
        totalprice: 0

    },
    reducers: {

        /**
         * 设置数据列表
         * @param state
         * @param payload
         * @returns {{list, page}}
         */
        setRecinvoicesList(state, { payload }) {
            return { ...state, list: payload.list, page: payload.page }
        },

        setInoviceproductsList(state, { payload }) {
            return { ...state, inoviceproductsList: payload.list, totalprice: payload.totalprice }
        },

        setTaxpreopeninvoice(state, { payload }) {
            return { ...state, taxpreopeninvoice: payload.taxpreopeninvoice }
        },


        setDataSource(state, action) {
            let payload = action.payload;
            return { ...state, dataSource: payload.dataSource };
        },

        setInoviceheader(state, action) {
            let payload = action.payload;
            return { ...state, inoviceheader: payload.inoviceheader };
        },

        /**
         * 设置开票人数据列表
         *
         * @param state
         * @param action
         */
        setDrawerList(state, { payload }) {
            return { ...state, drawerList: payload.drawerList };
        }

    },
    effects: {
        /**
         * 分页查询收票列表
         *
         * @param call
         * @param put
         * @param select
         */
        *getRecinvoicesList({ payload }, { call, put, select }) {

            let page = yield select(state => state.recinvoices.page);
            page = R.isNil(payload) || R.isNil(payload.page) ? page : payload.page;

            const res = yield call(getRecinvoicesList, {
                contractno: R.isNil(payload) || R.isNil(payload.contractno) ? "" : payload.contractno,
                openinvoicestatus: R.isNil(payload) || R.isNil(payload.status) ? "2" : payload.status,
                page: page
            })

            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                let listWithKey = R.isNil(content.list) ? [] : content.list;

                yield put({
                    type: 'setRecinvoicesList',
                    payload: {
                        list: listWithKey,
                        page: R.isNil(content.page) ? Constants.DEFAULTPAGE : content.page
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },


        /**
         *
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *getInoviceheaderByOrderId({ payload }, { call, put, select }) {
            const res = yield call(inoviceheader, { orderId: payload.orderId });

            if (res.data.resultCode === "ok") {
                let data = res.data.content;

                yield put({
                    type: "setInoviceheader",
                    payload: {
                        inoviceheader: data
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }

        },


        /**
         * 查询开票人下拉列表
         *
         * @param call
         * @param put
         * @param select
         */
        *queryDrawerList({ payload }, { call, put, select }) {
            const res = yield call(queryDrawers, { cstId: payload.cstId, status: "4" });
            if (res.data.resultCode === "ok") {
                let content = res.data.content;
                yield put({
                    type: 'setDrawerList',
                    payload: {
                        drawerList: R.isNil(content) ? [] : content,
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },

        /**
         *
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *getInoviceproductsByOrderId({ payload }, { call, put, select }) {
            const res = yield call(inoviceproducts, { orderId: payload.orderId });

            if (res.data.resultCode === "ok") {
                let data = res.data.content;
                let totalprice = 0;
                R.map((row) => {
                    if (!R.isNil(row.totalprice) && !R.isEmpty(!row.totalprice)) {
                        totalprice += row.totalprice;
                    }
                }, data);


                yield put({
                    type: "setInoviceproductsList",
                    payload: {
                        list: data,
                        totalprice: Math.round(totalprice * 10000) / 10000 //保留4位小数
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }

        },

        /**
         *
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *getTaxPreOpenInvoiceByOrderId({ payload }, { call, put, select }) {
            const res = yield call(taxpreopeninvoice, { orderId: payload.orderId });

            if (res.data.resultCode === "ok") {
                let data = res.data.content;
                yield put({
                    type: "setTaxpreopeninvoice",
                    payload: {
                        taxpreopeninvoice: data.taxpreopeninvoice
                    }
                });
            } else {
                message.error(res.data.errMessage);
            }
        },
        /**
         * 收票
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *receiveinvoice({ payload }, { call, put, select }) {

            let form = {
                orderId: payload.orderId,
                taxInvoiceFormList: payload.list,
                changeStatus: payload.changeStatus
            };

            const res = yield call(receiveinvoice, { form });
            if (res.data.resultCode === "ok") {
                message.info("收票成功！");

                if (payload.onSuccess) payload.onSuccess();

            } else {
                if (payload.onFail) payload.onFail();
                message.error(res.data.errMessage);
            }
        },


        /**
         * 审核
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *approval({ payload }, { call, put, select }) {
            const res = yield call(approval, payload);
            if (res.data.resultCode === "ok") {
                message.info("提交审核成功！");

                if (payload.onSuccess) payload.onSuccess();

            } else {
                if (payload.onFail) payload.onFail();
                message.error(res.data.errMessage);
            }
        },



        /**
         * 认证发票
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *checkinvoice({ payload }, { call, put, select }) {
            const res = yield call(checkinvoice, payload);
            if (res.data.resultCode === "ok") {
                message.info("提交成功！");

                if (payload.onSuccess) payload.onSuccess();

            } else {
                if (payload.onFail) payload.onFail();
                message.error(res.data.errMessage);
            }
        },

        /**
         * 删除发票
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *deleteInvoices({ payload }, { call, put, select }) {

            let inoviceheader = yield select(state => state.recinvoices.inoviceheader);
            let deleteReceiptno = null;
            if (!R.isNil(inoviceheader) && !R.isEmpty(inoviceheader) && !R.isNil(payload.receiptno)) {
                if (!R.isNil(inoviceheader[0].taxInvoices) && !R.isEmpty(R.isNil(inoviceheader[0].taxInvoices))) {
                    let taxInvoices = inoviceheader[0].taxInvoices;
                    for (let i = 0; i < taxInvoices.length; i++) {
                        let receiptno = taxInvoices[i].receiptno;
                        let tagreceiptno = payload.receiptno;

                        if (receiptno == tagreceiptno) {
                            deleteReceiptno = i;
                        }

                    }

                    if (deleteReceiptno != null) {
                        taxInvoices.splice(deleteReceiptno, 1);
                    }

                    inoviceheader[0].taxInvoices = taxInvoices;
                }

                yield put({
                    type: "setInoviceheader",
                    payload: {
                        inoviceheader: inoviceheader
                    }
                });

            }
        },

        /**
         * 更新发票
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *updateInvoices({ payload }, { call, put, select }) {

            let inoviceheader = yield select(state => state.recinvoices.inoviceheader);
            if (!R.isNil(inoviceheader) && !R.isEmpty(inoviceheader)) {
                if (!R.isNil(inoviceheader[0].taxInvoices) && !R.isEmpty(R.isNil(inoviceheader[0].taxInvoices))) {
                    let taxInvoices = inoviceheader[0].taxInvoices;
                    for (let i = 0; i < taxInvoices.length; i++) {
                        let id = taxInvoices[i].id;
                        let tagid = payload.record.id;

                        if (id == tagid) {
                            if(payload.type === "2") taxInvoices[i].amt = payload.value ? payload.value : 0;
                            if(payload.type === "1") taxInvoices[i].receiptno = payload.value ? payload.value : "";
                        }

                    }

                    inoviceheader[0].taxInvoices = taxInvoices;
                }

                yield put({
                    type: "setInoviceheader",
                    payload: {
                        inoviceheader: inoviceheader
                    }
                });

            }
        },


        /**
         * 增加发票
         * @param payload
         * @param call
         * @param put
         * @param select
         */
        *addInvoices({ payload }, { call, put, select }) {



            let num = payload.num;
            let inoviceheader = yield select(state => state.recinvoices.inoviceheader);
            let taxInvoices = [];
            if (!R.isNil(inoviceheader) && !R.isEmpty(inoviceheader) && !R.isNil(payload.receiptno)) {
                if (!R.isNil(inoviceheader[0].taxInvoices) && !R.isEmpty(R.isNil(inoviceheader[0].taxInvoices))) {

                    taxInvoices = inoviceheader[0].taxInvoices;
                    for (let i = 0; i < taxInvoices.length; i++) {
                        let receiptno = taxInvoices[i].receiptno;
                        let tagreceiptno = payload.receiptno;

                        for (let i = 0; i < num; i++) {
                            if (receiptno == tagreceiptno) {
                                message.error("发票号已存在");
                                return;
                            }
                            ++tagreceiptno;
                        }

                    }
                }

                if (!R.isNil(num)) {
                    let receiptno = payload.receiptno;
                    for (let i = 0; i < num; i++) {
                        let invoices = {
                            receiptno: receiptno,
                            drawername: payload.drawername,
                            createtime: payload.createtime,
                            orderid: payload.orderId,
                            openinvoicestatus: "2",
                            id: Constants.TEMP_ID_PRE + (payload.tempId + i)
                        };
                        ++receiptno;
                        taxInvoices.push(invoices);
                    }
                }

                inoviceheader[0].taxInvoices = taxInvoices;

                yield put({
                    type: "setInoviceheader",
                    payload: {
                        inoviceheader: inoviceheader
                    }
                });
                if (payload.onSuccess) payload.onSuccess();
            }

        },
        
        /**
         * 批量认证发票
         */
        *batchCheckinvoice({ payload }, { call }) {
            const res = yield call(batchCheckinvoice, { ...R.omit(['onSuccess', 'onFail'])(payload) });
            if (res.data.resultCode === "ok") {
                message.info("批量认证成功！");
                if (payload.onSuccess) payload.onSuccess();
            } else {
                if (payload.onFail) payload.onFail();
                message.error(res.data.errMessage);
            }
        },

    }, subscriptions: {
        setup({ history, dispatch }) {

        }
    }
};